package com.etc.service.impl;

import com.etc.dao.UserDao;
import com.etc.entity.User;
import com.etc.service.UserService;
import com.etc.util.MD5Util;
import com.etc.util.Message;
import com.etc.util.PageData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by Administrator on 2019/5/21.
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    /**
     * 分页查询（李添杭）
     *
     * @param page    页码
     * @param limit   显示数
     * @param content 模糊查询字段
     * @return
     */
    @Override
    public PageData<User> getPageData(Integer page, Integer limit, String content) {

        Pageable pageable = new PageRequest(page, limit);
        Page<User> userPage = userDao.findByLike(content, pageable);
        List<User> list = userPage.getContent();
        int count = (int) userPage.getTotalElements();
        PageData pd = new PageData(list, count, limit, page);
        return pd;
    }

    /**
     * 用户后台更新（李添杭）
     *
     * @param user 用户对象
     * @return
     */
    @Override
    public boolean updateUser(User user) {
        try {
            userDao.save(user);
            return true;

        } catch (Exception e) {
            return false;
        }

    }

    /**
     * dzq
     *
     * @param userid 用户id
     * @return User
     */
    @Override
    public User getUserByuserid(Integer userid) {
        return userDao.findOne(userid);
    }


    @Override
    public User findUserByTel(String usertel) {
        return userDao.findByUserTel(usertel);
    }


    @Override
    public boolean addUser(User user) {
        String str = MD5Util.getEncodeByMd5(user.getUserpassword());
        User us = new User(user.getUsername(), str, user.getUsertel(), 1);
        userDao.save(us);
        boolean flag = true;
        User u = userDao.findByUsername(user.getUsername());
        if (u == null) {
            flag = false;
        }
        return flag;
    }

    @Override
    public User findUserByUsername(String username) {
        return userDao.findByUsername(username);
    }

    @Override
    public Message findByUsernameAndUserpassword(String username, String userpassword) {
        Message message = new Message();
        String str = MD5Util.getEncodeByMd5(userpassword);
        User user = userDao.findByUsername(username);
        if (str.equals(user.getUserpassword())) {
            User u = userDao.findByUsernameAndUserpassword(username, str);
            if (u != null) {
                message.setMsg("登录成功");
            } else {
                message.setMsg("请注册");
            }

        } else {
            message.setMsg("密码错误");
        }
        return message;
    }
}
